import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  // url = base url + request url
  baseURL: process.env.VUE_APP_BASE_API,
  // TODO request timeout
  timeout: 1000 * 60 * 60
})

/**
 * 请求拦截器
 * 发送请求前做一些操作
 */
service.interceptors.request.use(
  config => {
    // 携带Token
    const isToken = (config.headers || {}).isToken === true
    if (getToken() && isToken) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    // GET请求参数映射
    if ((config.method === 'get' || config.method === 'GET') && config.params) {
      let url = config.url + '?' + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    return config
  },
  error => {
    // do something with request error
    console.log('请求错误信息: ' + error)
    return Promise.reject(error)
  }
)

/**
 * 响应拦截器
 * 对响应做一些处理
 */
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response

    // 未设置状态码则默认成功状态
    const statusCode = res.statusCode || 200;

    // 处理二进制流
    if (response.data instanceof Blob) {
      return res.data
    }

    if (statusCode === 401) {
      MessageBox.confirm('登录状态已过期, 请重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('LogOut').then(() => {
          location.href = '/index';
        })
      }).catch(() => {
      });
      return Promise.reject('无效的会话，或者会话已过期，请重新登录')
    } else if (statusCode === 500) {
      Message({
        message: msg,
        type: 'error'
      })
      return Promise.reject(new Error(msg))
    } else if (statusCode !== 200) {
      Notification.error({
        title: msg
      })
      return Promise.reject('error')
    } else {
      // 状态码是200
      return res.data
    }
  },

  error => {
    console.log('响应错误信息: ' + error)
    let {message} = error;
    if (message == "Network Error") {
      message = "系统接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = ''
  Object.keys(params).forEach((key) => {
    if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
      result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
    }
  })
  return result
}

export default service
